package com.estar.workparent.controller;


import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.dao.jdbc.JdbcDao;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSRoleUser;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;

import org.jeecgframework.core.util.ResourceUtil;

import com.estar.app.business.mobileLogin.entity.AppUserEntity;
import com.estar.workparent.entity.TmblWorktimeParentEntity;
import com.estar.workparent.service.TmblWorktimeParentServiceI;
import com.estar.workplace.entity.TmblWorkPlaceEntity;
import com.estar.worktime.controller.ExcelWorkTimeTable;
import com.estar.worktime.entity.TmblWorktimeEntity;
import com.estar.worktime.entity.WorkPlaceAndDataVo;
import com.estar.worktime.service.TmblWorktimeServiceI;

/**   
 * @Title: Controller  
 * @Description: TMBL_WORKTIME_PARENT
 * @author onlineGenerator
 * @date 2017-04-06 14:33:42
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/tmblWorktimeParentController")
@Scope("prototype")
public class TmblWorktimeParentController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TmblWorktimeParentController.class);
	private DateFormat d=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private TmblWorktimeParentServiceI tmblWorktimeParentService;
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private JdbcDao jdbcDao;
	
	@Autowired
	private TmblWorktimeServiceI tmblWorktimeService;

	@Autowired
	private ExcelWorkTimeTable excel;
	/**
	 * TMBL_WORKTIME_PARENT列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		
		return new ModelAndView("gdia/workparent/tmblWorktimeParentList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(TmblWorktimeParentEntity tmblWorktimeParent,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TmblWorktimeParentEntity.class, dataGrid);
		//查询条件组装器
		String arrwork = tmblWorktimeParent.getArrangework();
		if(StringUtil.isNotEmpty(arrwork)){
			String arrwork1 = "%" + arrwork + "%";
			cq.like("arrangework", arrwork1);
		}
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tmblWorktimeParent, request.getParameterMap());
		try{
			cq.addOrder("arrangework", SortDirection.desc);
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tmblWorktimeParentService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除TMBL_WORKTIME_PARENT
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	@Transactional
	public String doDel(TmblWorktimeParentEntity tmblWorktimeParent, HttpServletRequest request) {
		String id=request.getParameter("id");
		String message = null;
		//AjaxJson j = new AjaxJson();
		tmblWorktimeParent = systemService.getEntity(TmblWorktimeParentEntity.class, id);
		message = "排班表删除成功";
		try{
			List<TmblWorktimeEntity> wTable= tmblWorktimeService.findByProperty(TmblWorktimeEntity.class, "parentId", id);
			if(wTable !=null && wTable.size()>0){
				for(TmblWorktimeEntity w:wTable){
					tmblWorktimeService.delete(w);
				}
			}
			tmblWorktimeParentService.delete(tmblWorktimeParent);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			logger.error("删除排班表的系统错误",e);
			message = "排班表删除失败";
			throw new BusinessException(e.getMessage());
		}
		//j.setMsg(message);
		boolean flag=true;
		String json="{\"msg\":\""+message+"\",\"success\":"+flag+"}";
		return json;
	}
	
	/**
	 * 批量删除TMBL_WORKTIME_PARENT
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "TMBL_WORKTIME_PARENT删除成功";
		try{
			for(String id:ids.split(",")){
				TmblWorktimeParentEntity tmblWorktimeParent = systemService.getEntity(TmblWorktimeParentEntity.class, 
				id
				);
				tmblWorktimeParentService.delete(tmblWorktimeParent);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "TMBL_WORKTIME_PARENT删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加TMBL_WORKTIME_PARENT
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public String doAdd(TmblWorktimeParentEntity tmblWorktimeParent, String number,String wId,String wName,HttpServletRequest request) {
		String message = null;
		//AjaxJson j = new AjaxJson();
		boolean flag = true;
		try{
			
			String name=tmblWorktimeParent.getArrangework();
			tmblWorktimeParent.setDay(name);
			tmblWorktimeParent.setArrangework(name+"的排班表"+number);
			TSUser user2 = ResourceUtil.getSessionUserName();
			tmblWorktimeParent.setCreatename(user2.getRealName());
			tmblWorktimeParent.setCreatedate(new Date());
			tmblWorktimeParent.setCreateUserName(user2.getUserName());
			tmblWorktimeParentService.save(tmblWorktimeParent);//保存父类
			
			
			List<String> datasList=new ArrayList<String>();
			List<WorkPlaceAndDataVo> wdList=new ArrayList<WorkPlaceAndDataVo>();
			TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", tmblWorktimeParent.getId());
			
			if(twp!=null){
				String day=twp.getDay();
				String year=day.substring(0, day.indexOf("-"));
				String month=day.substring(day.indexOf("-")+1, day.length());
				List<String> daysList=days(year,month);
				datasList=datas(year,month);
				
			}else{
				flag=false;
			}
			
			if(datasList!=null && datasList.size()>0){
				String ids=wId;
				String[] strArray=null;
				strArray=ids.split(",");
				CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class);
				cq.isNotNull("tmblWorkPlace");
				cq.eq("isWork", "1");
				cq.in("id", strArray);
				cq.add();
				List<TmblWorkPlaceEntity> workPlaceList=this.systemService.getListByCriteriaQuery(cq, false);	
				TSUser u = ResourceUtil.getSessionUserName();
				for(TmblWorkPlaceEntity wp:workPlaceList){
					for(String day:datasList){
						TmblWorktimeEntity tw=new TmblWorktimeEntity();
						tw.setWorkplace(wp.getWorkplace());
						tw.setWorkPlaceId(wp.getId());
						tw.setParentId(twp.getId());
						tw.setWorkdate(d.parse(day));
						tw.setCreateName(u.getUserName());
						tw.setCreateDate(new Date());
						tw.setState("1");
						this.systemService.save(tw);
					}
				}
				//j.setMsg(twp.getId());
				message=twp.getId();
				
			}else{
				flag=false;
			}
			
			
		}catch(Exception e){
			flag=false;
			logger.error("保存排班表失败："+e);
			throw new BusinessException(e.getMessage());
		}
		String json="{\"msg\":\""+message+"\",\"success\":"+flag+"}";
		return json;
	}
	
	/**
	 * 更新TMBL_WORKTIME_PARENT
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public String doUpdate(TmblWorktimeParentEntity tmblWorktimeParent, HttpServletRequest request) {
		String message = null;
		//AjaxJson j = new AjaxJson();
		message = "排班总览表更新成功";
		
		try {
			String name=tmblWorktimeParent.getArrangework();
			tmblWorktimeParent.setDay(name);
			tmblWorktimeParent.setArrangework(name+"的排班表");
			TSUser user2 = ResourceUtil.getSessionUserName();
			tmblWorktimeParent.setUpdatename(user2.getUserName());
			tmblWorktimeParent.setUpdatedate(new Date());
			tmblWorktimeParentService.updateEntitie(tmblWorktimeParent);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "排班总览表更新失败";
			throw new BusinessException(e.getMessage());
		}
		//j.setMsg(message);
		boolean flag=true;
		String json="{\"msg\":\""+message+"\",\"success\":"+flag+"}";
		return json;
	}
	

	/**
	 * TMBL_WORKTIME_PARENT新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(TmblWorktimeParentEntity tmblWorktimeParent, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tmblWorktimeParent.getId())) {
			tmblWorktimeParent = tmblWorktimeParentService.getEntity(TmblWorktimeParentEntity.class, tmblWorktimeParent.getId());
			req.setAttribute("tmblWorktimeParentPage", tmblWorktimeParent);
		}
		return new ModelAndView("gdia/workparent/tmblWorktimeParent-add");
	}
	/**
	 * TMBL_WORKTIME_PARENT编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(TmblWorktimeParentEntity tmblWorktimeParent, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tmblWorktimeParent.getId())) {
			tmblWorktimeParent = tmblWorktimeParentService.getEntity(TmblWorktimeParentEntity.class, tmblWorktimeParent.getId());		
			req.setAttribute("tmblWorktimeParentPage", tmblWorktimeParent);
		}
		return new ModelAndView("gdia/workparent/tmblWorktimeParent-update");
	}
	/*@RequestMapping(params = "openWorkTable")
	public ModelAndView openWorkTable(TmblWorktimeParentEntity tmblWorktimeParent, HttpServletRequest req) {
		String id=req.getParameter("id");
		List<String> datasList=new ArrayList<String>();
		List<WorkPlaceAndDataVo> wdList=new ArrayList<WorkPlaceAndDataVo>();
		TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", id);
		
		if(twp!=null){
			String day=twp.getDay();
			String year=day.substring(0, day.indexOf("-"));
			String month=day.substring(day.indexOf("-")+1, day.length());
			List<String> daysList=days(year,month);
			datasList=datas(year,month);
			req.setAttribute("daysList", daysList);//日期天数的list
		}
		
		if(datasList!=null && datasList.size()>0){
			String ids=req.getParameter("workPlaceId");
			String[] strArray=null;
			strArray=ids.split(",");
			CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class);
			cq.isNotNull("tmblWorkPlace");
			cq.eq("isWork", "1");
			cq.in("id", strArray);
			cq.add();
			List<TmblWorkPlaceEntity> workPlaceList=this.systemService.getListByCriteriaQuery(cq, false);	
			wdList=new ArrayList<WorkPlaceAndDataVo>();
			for(TmblWorkPlaceEntity wp : workPlaceList){
				WorkPlaceAndDataVo wdvo=new WorkPlaceAndDataVo();
				wdvo.setWorkPlaceId(wp.getId());
				wdvo.setWorkPlaceName(wp.getWorkplace());
				wdvo.setDataList(datasList);
				wdList.add(wdvo);
			}
		}
		req.setAttribute("wdataList", wdList);
		req.setAttribute("pId", id);
		return new ModelAndView("gdia/worktime/workTable");
	}
	*/
	@RequestMapping(params = "check")
	@ResponseBody
	public String check(TmblWorktimeParentEntity tmblWorktimeParent, HttpServletRequest req){
		String message = "";
		
		boolean flag=true;
		try{
			String id=req.getParameter("id");
			TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", id);
			if(twp!=null){
				List<String> wids=new ArrayList<String>();
				TSUser u = ResourceUtil.getSessionUserName();List<TSRoleUser> rus=this.systemService.findByProperty(TSRoleUser.class, "TSUser.id", u.getId());
				if(rus.size()>0 && rus!=null){
				    String key=rus.get(0).getTSRole().getRoleCode();
				    if(!key.equals("01") && !key.equals("admin")){//管理员和省保协可以搞全部
				    	//判断用户
						CriteriaQuery tcq = new CriteriaQuery(TmblWorktimeEntity.class);
						tcq.setProjection(Property.forName("workPlaceId"));
						tcq.eq("createName", u.getUserName());
						tcq.eq("parentId", id);
						tcq.add();
						wids=systemService.getListByCriteriaQuery(tcq, false);
						if(wids!=null && wids.size()>0){
							
						}else{
							message="不能修改不属于自己的排班表！";
							flag=false;
						}
				    }
				}
				
			}else{
				
				message="请录入排班表";
				flag=false;
			}
		}catch(Exception e){
			message="检查排班check系统错误";
			flag=false;
			logger.error("检查排班check系统错误",e);
		}
		String json="{\"msg\":\""+message+"\",\"success\":"+flag+"}";
		return json;
	}
	
	@RequestMapping(params = "updateWorkTable")
	public ModelAndView updateWorkTable(TmblWorktimeParentEntity tmblWorktimeParent, HttpServletRequest req) {
		String mess=req.getParameter("mess");
		try{
			//查看汇总排班表
			if(mess.equals("show")){
				show(req);
			}
			//看自己
			if(mess.equals("showMyself")){
				showMySelf(req);
			}
			//编辑排班表
			if(mess.equals("update")){
				
				updateMess(req,mess);
			}
			req.setAttribute("mess", req.getParameter("mess"));
			req.setAttribute("name", req.getParameter("name"));
		}catch (Exception e) {
			logger.error("排班总览表更新系统错误：",e);
		}
		if(mess.equals("update")){
			return new ModelAndView("gdia/worktime/workTableUpdate");
		}else if(mess.equals("show")){
			return new ModelAndView("gdia/worktime/workTableShow");
		}else if(mess.equals("showMyself")){
			return new ModelAndView("gdia/worktime/workTableShow");
		}else{
			return new ModelAndView("gdia/worktime/workTableShow");
		}
	}
	
	private void show(HttpServletRequest req){
		String id=req.getParameter("id");
		List<String> datasList=new ArrayList<String>();
		List<WorkPlaceAndDataVo> wdList=new ArrayList<WorkPlaceAndDataVo>();
		List<TmblWorktimeEntity> newList=new ArrayList<TmblWorktimeEntity>();
		TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", id);
		
		if(twp!=null){
			String day=twp.getDay();
			String year=day.substring(0, day.indexOf("-"));
			String month=day.substring(day.indexOf("-")+1, day.length());
			List<String> daysList=days(year,month);
			req.setAttribute("daysList", daysList);//日期天数的list
			//获取所有父id
			String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+day+"'";
			List<String> idList=this.systemService.findListbySql(sql1);
			
			
			String sql="select id from tmbl_work_place where code='GZGS'";
			List<String> workPlacePid=this.systemService.findListbySql(sql);
			String pid=workPlacePid.get(0);
			CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class);
			cq.isNotNull("tmblWorkPlace");
			cq.eq("isWork", "1");
			cq.notEq("tmblWorkPlace.id", pid);
			cq.addOrder("id", SortDirection.asc);
			cq.add();
			List<TmblWorkPlaceEntity> workPlaceList=this.systemService.getListByCriteriaQuery(cq, false);	
			wdList=new ArrayList<WorkPlaceAndDataVo>();
			for(TmblWorkPlaceEntity wp : workPlaceList){
				WorkPlaceAndDataVo wdvo=new WorkPlaceAndDataVo();
				wdvo.setWorkPlaceId(wp.getId());
				wdvo.setWorkPlaceName(wp.getWorkplace());
				CriteriaQuery cq1 = new CriteriaQuery(TmblWorktimeEntity.class);
				cq1.in("parentId", idList.toArray());
				cq1.eq("workPlaceId", wp.getId());
				cq1.eq("state", "1");
				cq1.addOrder("workdate", SortDirection.asc);
				cq1.add();
				List<TmblWorktimeEntity> wTable= tmblWorktimeService.getListByCriteriaQuery(cq1, false);
				wdvo.setWtime(wTable);
				wdList.add(wdvo);
			}
			
			//装载新增的排班信息
			CriteriaQuery cq2 = new CriteriaQuery(TmblWorktimeEntity.class);
			cq2.in("parentId", idList.toArray());
			cq2.eq("state", "2");
			cq2.addOrder("workdate", SortDirection.asc);
			cq2.add();
			newList=tmblWorktimeService.getListByCriteriaQuery(cq2, false);
			
			String ss="";
			for(String s:idList){
				ss+="'"+s+"',";
			}
			ss=ss.substring(0, ss.lastIndexOf(','));
			String sql2="SELECT w.EMPNAME name,count(w.EMPNAME) num from TMBL_WORKTIME w where w.PARENTID in ("+ss+") and w.state <> '3' and w.EMPNAME is not null GROUP by (w.EMPNAME)";
		
			List<Map<String, Object>> tongji=jdbcDao.findForJdbc(sql2);
			
			req.setAttribute("tongji", tongji);
		}
		
		req.setAttribute("newdataList", newList);
		req.setAttribute("wdataList", wdList);
		req.setAttribute("pId", id);
	}
	
	//看自己的排班信息
	private void showMySelf(HttpServletRequest req) throws UnsupportedEncodingException{
		String id=req.getParameter("id");
		String name = new String(req.getParameter("name").getBytes("iso-8859-1"), "utf-8"); 
		//String name=req.getParameter("name");
		List<String> datasList=new ArrayList<String>();
		List<WorkPlaceAndDataVo> wdList=new ArrayList<WorkPlaceAndDataVo>();
		List<TmblWorktimeEntity> newList=new ArrayList<TmblWorktimeEntity>();
		
		TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", id);
		
		if(twp!=null){
			String day=twp.getDay();
			String year=day.substring(0, day.indexOf("-"));
			String month=day.substring(day.indexOf("-")+1, day.length());
			List<String> daysList=days(year,month);
			req.setAttribute("daysList", daysList);//日期天数的list
			
			List<String> wids=new ArrayList<String>();
			//只能看自己录入的 
			
				TSUser u = ResourceUtil.getSessionUserName();
				
				List<TSRoleUser> rus=this.systemService.findByProperty(TSRoleUser.class, "TSUser.id", u.getId());
				if(rus.size()>0 && rus!=null){
				    String key=rus.get(0).getTSRole().getRoleCode();
				    if(!key.equals("01") && !key.equals("admin")){
				    	CriteriaQuery tcq = new CriteriaQuery(TmblWorktimeEntity.class);
						tcq.setProjection(Property.forName("workPlaceId"));
						tcq.eq("createName", u.getUserName());
						tcq.eq("parentId", id);
						tcq.eq("state", "1");
						tcq.add();
						wids=systemService.getListByCriteriaQuery(tcq, false);
				    }else{
				    	CriteriaQuery tcq = new CriteriaQuery(TmblWorktimeEntity.class);
						tcq.setProjection(Property.forName("workPlaceId"));
						if(name.equals("bb")){
							tcq.eq("createName", u.getUserName());
						}else{
							
							tcq.eq("createName", name);
						}
						tcq.eq("parentId", id);
						tcq.eq("state", "1");
						tcq.add();
						wids=systemService.getListByCriteriaQuery(tcq, false);
				    }
				}
				
				
				
			String sql="select id from tmbl_work_place where code='GZGS'";
			List<String> workPlacePid=this.systemService.findListbySql(sql);
			String pid=workPlacePid.get(0);
			CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class);
			if(wids!=null && wids.size()>0){
				cq.in("id", wids.toArray());
				cq.addOrder("id", SortDirection.asc);
			}else{
				cq.isNotNull("tmblWorkPlace");
				cq.eq("isWork", "1");
				cq.notEq("tmblWorkPlace.id", pid);
				cq.addOrder("id", SortDirection.asc);
			}
			cq.add();
			List<TmblWorkPlaceEntity> workPlaceList=this.systemService.getListByCriteriaQuery(cq, false);	
			wdList=new ArrayList<WorkPlaceAndDataVo>();
			for(TmblWorkPlaceEntity wp : workPlaceList){
				WorkPlaceAndDataVo wdvo=new WorkPlaceAndDataVo();
				wdvo.setWorkPlaceId(wp.getId());
				wdvo.setWorkPlaceName(wp.getWorkplace());
				CriteriaQuery cq1 = new CriteriaQuery(TmblWorktimeEntity.class);
				cq1.eq("parentId", id);
				cq1.eq("workPlaceId", wp.getId());
				cq1.eq("state", "1");
				cq1.addOrder("workdate", SortDirection.asc);
				cq1.add();
				List<TmblWorktimeEntity> wTable= tmblWorktimeService.getListByCriteriaQuery(cq1, false);
				wdvo.setWtime(wTable);
				wdList.add(wdvo);
			}
			//装载新增的排班信息
			CriteriaQuery cq2 = new CriteriaQuery(TmblWorktimeEntity.class);
			cq2.eq("parentId", id);
			cq2.eq("state", "2");
			cq2.addOrder("workdate", SortDirection.asc);
			cq2.add();
			newList=tmblWorktimeService.getListByCriteriaQuery(cq2, false);
			
			
			
			String sql2="SELECT w.EMPNAME name,count(w.EMPNAME) num from TMBL_WORKTIME w where w.PARENTID = '"+id+"' and w.state <>'3' and w.EMPNAME is not null GROUP by (w.EMPNAME)";
		
			List<Map<String, Object>> tongji=jdbcDao.findForJdbc(sql2);
			
			req.setAttribute("tongji", tongji);
		}
		req.setAttribute("newdataList", newList);
		req.setAttribute("wdataList", wdList);
		req.setAttribute("pId", id);
	}
	//看自己的排班信息---------end
	
	
	//更新排班信息
	private void updateMess(HttpServletRequest req,String mess){
		String name=req.getParameter("name");
		TSUser u = ResourceUtil.getSessionUserName();
		List<TSRoleUser> rus=this.systemService.findByProperty(TSRoleUser.class, "TSUser.id", u.getId());
		if(rus.size()>0 && rus!=null){
		    String key=rus.get(0).getTSRole().getRoleCode();
		   /* if(!key.equals("01") && !key.equals("admin")){//管理员和保协人员可以编辑全部
*/		    	
		    	//区域经理
		    	String id=req.getParameter("id");
				List<String> datasList=new ArrayList<String>();
				List<WorkPlaceAndDataVo> wdList=new ArrayList<WorkPlaceAndDataVo>();
				List<TmblWorktimeEntity> newList=new ArrayList<TmblWorktimeEntity>();
				
				TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", id);
				
				if(twp!=null){
					String day=twp.getDay();
					String year=day.substring(0, day.indexOf("-"));
					String month=day.substring(day.indexOf("-")+1, day.length());
					List<String> daysList=days(year,month);
					req.setAttribute("daysList", daysList);//日期天数的list
					
					List<String> wids=new ArrayList<String>();
					if(mess.equals("update")){
						
						CriteriaQuery tcq = new CriteriaQuery(TmblWorktimeEntity.class);
						tcq.setProjection(Property.forName("workPlaceId"));
						if(!key.equals("01") && !key.equals("admin")){
							tcq.eq("createName", u.getUserName());
						}else{
							if(name.equals("bb")){
								tcq.eq("createName", u.getUserName());
							}else{
								tcq.eq("createName", name);
							}
						}
						tcq.eq("state", "1");
						tcq.eq("parentId", id);
						tcq.add();
						wids=systemService.getListByCriteriaQuery(tcq, false);
					}
					String sql="select id from tmbl_work_place where code='GZGS'";
					List<String> workPlacePid=this.systemService.findListbySql(sql);
					String pid=workPlacePid.get(0);
					CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class);
					if(wids!=null && wids.size()>0){
						cq.in("id", wids.toArray());
						cq.addOrder("id", SortDirection.asc);
					}else{
						cq.isNotNull("tmblWorkPlace");
						cq.eq("isWork", "1");
						cq.notEq("tmblWorkPlace.id", pid);
						cq.addOrder("id", SortDirection.asc);
					}
					cq.add();
					List<TmblWorkPlaceEntity> workPlaceList=this.systemService.getListByCriteriaQuery(cq, false);	
					wdList=new ArrayList<WorkPlaceAndDataVo>();
					for(TmblWorkPlaceEntity wp : workPlaceList){
						WorkPlaceAndDataVo wdvo=new WorkPlaceAndDataVo();
						wdvo.setWorkPlaceId(wp.getId());
						wdvo.setWorkPlaceName(wp.getWorkplace());
						CriteriaQuery cq1 = new CriteriaQuery(TmblWorktimeEntity.class);
						cq1.eq("parentId", id);
						cq1.eq("workPlaceId", wp.getId());
						cq1.eq("state", "1");
						cq1.addOrder("workdate", SortDirection.asc);
						cq1.add();
						List<TmblWorktimeEntity> wTable= tmblWorktimeService.getListByCriteriaQuery(cq1, false);
						wdvo.setWtime(wTable);
						wdList.add(wdvo);
					}
					//装载新增的排班信息
					CriteriaQuery cq2 = new CriteriaQuery(TmblWorktimeEntity.class);
					cq2.eq("parentId", id);
					cq2.eq("state", "2");
					cq2.addOrder("workdate", SortDirection.asc);
					cq2.add();
					newList=tmblWorktimeService.getListByCriteriaQuery(cq2, false);
				}
				req.setAttribute("newdataList", newList);
				req.setAttribute("wdataList", wdList);
				req.setAttribute("pId", id);
		  /*  }else{*/
		    	
		    	/*//管理员和保协人员
		    	String id=req.getParameter("id");
				List<String> datasList=new ArrayList<String>();
				List<WorkPlaceAndDataVo> wdList=new ArrayList<WorkPlaceAndDataVo>();
				List<TmblWorktimeEntity> newList=new ArrayList<TmblWorktimeEntity>();
				
				TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", id);
				
				if(twp!=null){
					String day=twp.getDay();
					String year=day.substring(0, day.indexOf("-"));
					String month=day.substring(day.indexOf("-")+1, day.length());
					List<String> daysList=days(year,month);
					req.setAttribute("daysList", daysList);//日期天数的list
					//获取所有父id
					String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+day+"'";
					
					List<String> wids=new ArrayList<String>();
					if(mess.equals("update")){
						TSUser uu = ResourceUtil.getSessionUserName();
						CriteriaQuery tcq = new CriteriaQuery(TmblWorktimeEntity.class);
						tcq.setProjection(Property.forName("workPlaceId"));
						tcq.eq("createName", name);
						tcq.eq("state", "1");
						tcq.eq("parentId", id);
						tcq.add();
						wids=systemService.getListByCriteriaQuery(tcq, false);
					}
					
					
					String sql="select id from tmbl_work_place where code='GZGS'";
					List<String> workPlacePid=this.systemService.findListbySql(sql);
					String pid=workPlacePid.get(0);
					CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class);
					cq.isNotNull("tmblWorkPlace");
					cq.eq("isWork", "1");
					cq.notEq("tmblWorkPlace.id", pid);
					cq.addOrder("id", SortDirection.asc);
					cq.add();
					//获取服务点信息
					List<TmblWorkPlaceEntity> workPlaceList=this.systemService.getListByCriteriaQuery(cq, false);	
					//装载排班信息
					for(TmblWorkPlaceEntity wp : workPlaceList){
						WorkPlaceAndDataVo wdvo=new WorkPlaceAndDataVo();
						wdvo.setWorkPlaceId(wp.getId());
						wdvo.setWorkPlaceName(wp.getWorkplace());
						CriteriaQuery cq1 = new CriteriaQuery(TmblWorktimeEntity.class);
						cq1.in("parentId", idList.toArray());
						cq1.eq("workPlaceId", wp.getId());
						cq1.eq("state", "1");
						cq1.addOrder("workdate", SortDirection.asc);
						cq1.add();
						List<TmblWorktimeEntity> wTable= tmblWorktimeService.getListByCriteriaQuery(cq1, false);
						wdvo.setWtime(wTable);
						wdList.add(wdvo);
					
					}
					
					//装载新增的排班信息
					CriteriaQuery cq2 = new CriteriaQuery(TmblWorktimeEntity.class);
					cq2.in("parentId", idList.toArray());
					cq2.eq("state", "2");
					cq2.addOrder("workdate", SortDirection.asc);
					cq2.add();
					newList=tmblWorktimeService.getListByCriteriaQuery(cq2, false);
				}
				req.setAttribute("newdataList", newList);
				req.setAttribute("wdataList", wdList);
				req.setAttribute("pId", id);*/
		  /*  }*/
		}
	}
	//更新排班信息------end
	
	@RequestMapping(params = "excelTable")
	public void excelTable(HttpServletRequest request, HttpServletResponse response){
		
		String id=request.getParameter("id");
		String name=request.getParameter("name");
		
		if(StringUtil.isEmpty(name)){//打印全部的排班表
			//找出哪些是要打印的信息
			TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", id);
			String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+twp.getDay()+"'";
			
			List<String> lis=this.systemService.findListbySql(sql1);
			List<TmblWorktimeEntity> newList=new ArrayList<TmblWorktimeEntity>();
			
			List<WorkPlaceAndDataVo> wdList=new ArrayList<WorkPlaceAndDataVo>();
			if(twp!=null){
				//日期排序
				String day=twp.getDay();
				String year=day.substring(0, day.indexOf("-"));
				String month=day.substring(day.indexOf("-")+1, day.length());
				List<String> daysList=days(year,month);
				
				//找出打印的服务点
				String sql="select id from tmbl_work_place where code='GZGS'";
				List<String> workPlacePid=this.systemService.findListbySql(sql);
				String pid=workPlacePid.get(0);
				CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class);
				cq.isNotNull("tmblWorkPlace");
				cq.eq("isWork", "1");
				cq.notEq("tmblWorkPlace.id", pid);
				cq.addOrder("id", SortDirection.asc);
				cq.add();
				List<TmblWorkPlaceEntity> workPlaceList=this.systemService.getListByCriteriaQuery(cq, false);	
				//查找对应服务点的排班信息，也就是排班信息获取
				wdList=new ArrayList<WorkPlaceAndDataVo>();
				for(TmblWorkPlaceEntity wp : workPlaceList){
					WorkPlaceAndDataVo wdvo=new WorkPlaceAndDataVo();
					wdvo.setWorkPlaceId(wp.getId());
					wdvo.setWorkPlaceName(wp.getWorkplace());
					CriteriaQuery cq1 = new CriteriaQuery(TmblWorktimeEntity.class);
					cq1.in("parentId", lis.toArray());
					cq1.eq("workPlaceId", wp.getId());
					cq1.eq("state", "1");
					cq1.addOrder("workdate", SortDirection.asc);
					cq1.add();
					List<TmblWorktimeEntity> wTable= tmblWorktimeService.getListByCriteriaQuery(cq1, false);
					wdvo.setWtime(wTable);
					wdList.add(wdvo);
				}
				
				
				//对应新增的排班信息
				
				CriteriaQuery cq2 = new CriteriaQuery(TmblWorktimeEntity.class);
				cq2.in("parentId", lis.toArray());
				cq2.eq("state", "2");
				cq2.addOrder("workdate", SortDirection.asc);
				cq2.add();
				newList=tmblWorktimeService.getListByCriteriaQuery(cq2, false);
				
				excel.excelTable(twp.getArrangework(),twp.getDay(), request, response, daysList, wdList,newList);
			}
			
		}else{//打印各自的排版表
			
			TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", id);
			/*String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+twp.getDay()+"'";
			List<String> lis=this.systemService.findListbySql(sql1);//
*/			
			List<TmblWorktimeEntity> newList=new ArrayList<TmblWorktimeEntity>();
			List<WorkPlaceAndDataVo> wdList=new ArrayList<WorkPlaceAndDataVo>();
			if(twp!=null){
				String day=twp.getDay();
				String year=day.substring(0, day.indexOf("-"));
				String month=day.substring(day.indexOf("-")+1, day.length());
				List<String> daysList=days(year,month);
				
				List<String> wids=new ArrayList<String>();
					CriteriaQuery tcq = new CriteriaQuery(TmblWorktimeEntity.class);
					tcq.setProjection(Property.forName("workPlaceId"));
					tcq.eq("createName", name);
					tcq.eq("parentId", id);
					tcq.eq("state", "1");
					tcq.add();
					wids=systemService.getListByCriteriaQuery(tcq, false);
				
				
				CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class);
				cq.in("id", wids.toArray());
				cq.eq("isWork", "1");
				cq.addOrder("id", SortDirection.asc);
				cq.add();
				List<TmblWorkPlaceEntity> workPlaceList=this.systemService.getListByCriteriaQuery(cq, false);	
				wdList=new ArrayList<WorkPlaceAndDataVo>();
				for(TmblWorkPlaceEntity wp : workPlaceList){
					WorkPlaceAndDataVo wdvo=new WorkPlaceAndDataVo();
					wdvo.setWorkPlaceId(wp.getId());
					wdvo.setWorkPlaceName(wp.getWorkplace());
					CriteriaQuery cq1 = new CriteriaQuery(TmblWorktimeEntity.class);
					cq1.eq("parentId", id);
					cq1.eq("workPlaceId", wp.getId());
					cq1.addOrder("workdate", SortDirection.asc);
					cq1.eq("state", "1");
					cq1.add();
					List<TmblWorktimeEntity> wTable= tmblWorktimeService.getListByCriteriaQuery(cq1, false);
					wdvo.setWtime(wTable);
					wdList.add(wdvo);
				}
				
				//对应新增的排班信息
				CriteriaQuery cq2 = new CriteriaQuery(TmblWorktimeEntity.class);
				cq2.eq("parentId", id);
				cq2.in("workPlaceId", wids.toArray());
				cq2.eq("state", "2");
				cq2.addOrder("workdate", SortDirection.asc);
				cq2.add();
				newList=tmblWorktimeService.getListByCriteriaQuery(cq2, false);
				
				
				
				excel.excelTable(twp.getArrangework(),twp.getDay(), request, response, daysList, wdList,newList);
			}
		}
	}
	
	
	//机构选择
	@RequestMapping(params = "goSelectDepart")
	 public String goSelectDepart(){
		   return "gdia/worktime/selectDepart";
	 }
	 @RequestMapping(params = "selectDepart")
	 public void selectDepart(TmblWorkPlaceEntity tmbldepart,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		 CriteriaQuery cq = new CriteriaQuery(TmblWorkPlaceEntity.class, dataGrid);
		 try{
			String sql="select id from tmbl_work_place where code='GZGS'";
			List<String> workPlacePid=this.systemService.findListbySql(sql);
			String pid=workPlacePid.get(0);
			
			if(StringUtil.isNotEmpty(tmbldepart.getWorkplace())){
				cq.like("workplace", "%"+tmbldepart.getWorkplace()+"%");
			}
			cq.isNotNull("tmblWorkPlace");
			cq.eq("isWork", "1");
			cq.notEq("tmblWorkPlace.id", pid);
			cq.add();
			}catch (Exception e) {
				throw new BusinessException(e.getMessage());
		}
			this.systemService.getDataGridReturn(cq, false);
			TagUtil.datagrid(response, dataGrid);
	}
	
	/* //检查用户是否重复
	 @RequestMapping(params = "checkName")
	 @ResponseBody
	 public AjaxJson  checkName(HttpServletRequest request, HttpServletResponse response){
		 String message = null;
			AjaxJson j = new AjaxJson();
			boolean flag=false;
			try{
				
			}catch(Exception e){
				message = "选择服务点失败！";
				logger.error("选择服务点系统异常："+e);
			}
			j.setMsg(message);
			j.setSuccess(flag);
			return j;
	 }*/
	 
	 //检查是否重复选择服务点
	 @RequestMapping(params = "checkDepart")
	 @ResponseBody
	 public AjaxJson  checkDepart(HttpServletRequest request, HttpServletResponse response){
		 String message = null;
			AjaxJson j = new AjaxJson();
			message = "选择服务点成功！";
			boolean flag=false;
			try{
				String wids=request.getParameter("workPlaceId");
				String arrangework = request.getParameter("arrangework");
				
				//TmblWorktimeParentEntity twp=this.tmblWorktimeParentService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", pid);
				//获取所有父id
				String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+arrangework+"'";
				List<String> idList=this.systemService.findListbySql(sql1);
				
				List<String> wte=new ArrayList<String>();
				if(idList!=null && idList.size()>0){
					String[] strArray=null;
					strArray=wids.split(",");
					CriteriaQuery tcq = new CriteriaQuery(TmblWorktimeEntity.class);
					tcq.setProjection(Property.forName("workplace"));
					tcq.in("parentId", idList.toArray());
					tcq.in("workPlaceId", strArray);
					tcq.notEq("state", "3");
					tcq.add();
					wte=this.systemService.getListByCriteriaQuery(tcq, false);
				}
				if(wte!=null && wte.size()>0){
					List<String> newWt=removeDuplicate(wte);
					StringBuffer sb=new StringBuffer();
					for(String s:newWt){
						sb.append(s);
						sb.append("、");
					}
					sb.deleteCharAt(sb.length()-1);
					message="本排班表已存在  "+sb.toString()+" 的排班信息，请重新选择服务点";
					flag=false;
				}else{
					flag=true;
				}
			}catch(Exception e){
				message = "选择服务点失败！";
				logger.error("选择服务点系统异常："+e);
			}
			j.setMsg(message);
			j.setSuccess(flag);
			return j;
	 }
	 //服务点去重
	    private  static   List<String>  removeDuplicate(List list)  {       
	        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {       
	            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {       
	                 if  (list.get(j).equals(list.get(i)))  {       
	                    list.remove(j);       
	                  }        
	              }        
	            }        
	          return list;       
	      }  
	//用户选择
		@RequestMapping(params = "goSelectAppUser")
	   public String goSelectAppUSer(){
		   return "gdia/worktime/selectAppUser";
	   }
	   
	 @RequestMapping(params = "selectAppUser")
	 public void datagrid(AppUserEntity tmblAppUser,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
			CriteriaQuery cq = new CriteriaQuery(AppUserEntity.class, dataGrid);
			
			String  empCde=tmblAppUser.getEmpCde();
			tmblAppUser.setEmpCde("");
			String empName=tmblAppUser.getEmpName();
			tmblAppUser.setEmpName("");
			//查询条件组装器
			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tmblAppUser, request.getParameterMap());
			try{
			//自定义追加查询条件
			//模糊查询
				if(empCde!=null && !empCde.equals("")){
					cq.like("empCde", "%"+empCde+"%");
				}
				if(empName!=null && !empName.equals("")){
					cq.like("empName", "%"+empName+"%");
				}
				cq.eq("statue", "1");//普通员工
				cq.eq("isWork", "1");//在职
				cq.eq("area", "1");
				cq.addOrder("id",SortDirection.desc);//列表加载显示的时候，按时间排序
				cq.add();
			}catch (Exception e) {
				throw new BusinessException(e.getMessage());
			}
			
			this.systemService.getDataGridReturn(cq, false);
			TagUtil.datagrid(response, dataGrid);
	}
	
	private List<String> days(String y,String m){//排班表头
		List<String> daysList=new ArrayList<String>();
		int allDay=0;
		int year=Integer.valueOf(y);
		int month=Integer.valueOf(m);
		byte a=(byte) month;
		switch (a) {
		case 1:case 3:case 5:case 7:case 8:case 10:case 12:
			allDay= 31;
			break;
			
		case 4:case 6:case 9:case 11:
			allDay= 30;
			break;
		case 2:
			if(year%4==0&&year%100!=0||year%400==0){
				allDay=  29;
				break;
			}else{
				allDay= 28;
				break;
			}
		
		default:
			allDay= 1;
		}
		if(allDay>0){
			for(int i=1;i<=allDay;i++){
				String data=i+"日";
				daysList.add(data);
			}
		}
		
		return daysList;
	}
	
	private List<String> datas(String y,String m){//工作的日期
		List<String> daysList=new ArrayList<String>();
		int allDay=0;
		int year=Integer.valueOf(y);
		int month=Integer.valueOf(m);
		byte a=(byte) month;
		switch (a) {
		case 1:case 3:case 5:case 7:case 8:case 10:case 12:
			allDay= 31;
			break;
			
		case 4:case 6:case 9:case 11:
			allDay= 30;
			break;
		case 2:
			if(year%4==0&&year%100!=0||year%400==0){
				allDay=  29;
				break;
			}else{
				allDay= 28;
				break;
			}
		
		default:
			allDay= 1;
		}
		if(allDay>0){
			for(int i=1;i<=allDay;i++){
				String d="0"+i;
				d=d.substring(d.length()-2, d.length());
				String data=y+"-"+m+"-"+d+" 00:00:00";
				daysList.add(data);
			}
		}
		
		return daysList;
	}
		
		
}
